import { _decorator, Component, Node } from 'cc';
import EventManager from '../../../Init/Managers/EventManager';
import { EventTypes } from '../../../Init/Managers/EventTypes';

const { ccclass, property } = _decorator;

// 游戏中微信延迟循环触发广告
@ccclass('WxDelayAd')
export class WxDelayAd extends Component {
    // 延迟时间
    private _wxDelayTime = 99999;
    onLoad(): void {
        // 监听事件
        EventManager.on(EventTypes.GameEvents.GameRun, this.onGameRun, this);
        EventManager.on(EventTypes.GameEvents.GameOver, this.onGameOver, this);
    }
    onEnable() {
        // 获取延迟配置时间
        // this._wxDelayTime = Number(wxsdk.GetConfigById('PopAdTimer')) || 99999; //秒

        if (this._wxDelayTime == 0) {
            this._wxDelayTime = 0.1;
        }
        console.log('# _wxDelayTime', this._wxDelayTime);
    }
    update(dt: number) {
        this.updateWXDelay(dt);
    }
    // 游戏开始
    onGameRun() {
        this.delayWXAdStart();
    }
    // 游戏结束
    onGameOver() {
        this.delayWXAdStop();
    }

    // #region -----------------wx延迟---
    private _isWxDelay = false;  // 延迟开关
    private _isAdNext = true;
    private _delayTime = 99999;  // 倒计时

    // 开启延迟
    private delayWXAdStart() {
        this._isWxDelay = true;
        this._delayTime = this._wxDelayTime;
        this._isAdNext = true;
    }
    // 停止延迟计时
    private delayWXAdStop() {
        this._isWxDelay = false;
        this._isAdNext = false;
        this._delayTime = 99999999;
    }
    // 延迟倒计时
    private updateWXDelay(dt) {

        if (this._isWxDelay && this._isAdNext) {
            this._delayTime -= dt;

            if (this._delayTime <= 0) {

                console.log('# PopAdTimer 1');
                // 阻塞循环
                this._isAdNext = false;
                // 暂停游戏
                EventManager.emit(EventTypes.GameEvents.GamePause);
                // 重置延迟倒计时
                this._delayTime = this._wxDelayTime;
                // 触发广告
                this.showAd();
            }
        }
    }

    private async showAd() {
        // 触发广告
        // await wxsdk.GetAdById('PopAdTimer');
        // 开启循环
        this._isAdNext = true;
        // 继续游戏
        EventManager.emit(EventTypes.GameEvents.GameResume);

        console.log('# PopAdTimer 2');
    }

    // #endregion
}

